package it.trekker.upload.json.ejb;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import it.trekker.converter.IJsonConverter;
import it.trekker.converter.JsonConverter;
import it.trekker.dao.Excursion;
import it.trekker.dao.ExcursionCoordinate;
import it.trekker.dao.IExcursionCoordinateDAO;
import it.trekker.dao.IExcursionDAO;
import it.trekker.dao.IPoiDAO;
import it.trekker.dao.IUserDAO;
import it.trekker.dao.Poi;
import it.trekker.dao.User;
import it.trekker.upload.IFileLoader2Database;
import it.trekker.upload.json.ExcursionAdapter;

import javax.ejb.Asynchronous;
import javax.ejb.EJB;
import javax.ejb.Remote;
import javax.ejb.Stateless;

@Stateless
@Asynchronous
@Remote(IFileLoader2Database.class)
public class JsonFile2Database implements IFileLoader2Database {

	@EJB(lookup="ejb:TrekkerServer/TrekkerServer.jar/EJB3ExcursionDAO!it.trekker.dao.IExcursionDAO")
	private IExcursionDAO excursionDAO;
	@EJB(lookup="ejb:TrekkerServer/TrekkerServer.jar/EJB3ExcursionCoordinateDAO!it.trekker.dao.IExcursionCoordinateDAO")
	private IExcursionCoordinateDAO excursionCoordDAO;
	@EJB(lookup="ejb:TrekkerServer/TrekkerServer.jar/EJB3PoiDAO!it.trekker.dao.IPoiDAO")
	private IPoiDAO poiDAO;
	@EJB(lookup="ejb:TrekkerServer/TrekkerServer.jar/EJB3UserDAO!it.trekker.dao.IUserDAO")
	private IUserDAO userDAO;
	
	public void extractData2Database(String filePath) {
		IJsonConverter converter = new JsonConverter();
		
		try {
			File jsonFile = new File(filePath);
			FileReader reader = new FileReader(jsonFile);
			ExcursionAdapter[] list = converter.JsonFile2ExcursionAdapterArray(reader);
			reader.close();
			jsonFile.delete();
			
			for(ExcursionAdapter excursionAdapter : list) {
				
				User user = excursionAdapter.getUser();
				user.setId(userDAO.insert(user));
				
				Excursion excursion = excursionAdapter.getExcursion();
				excursion.setUser(user);
				excursion.setId(excursionDAO.insert(excursion));
				
				List<ExcursionCoordinate> coordinates = excursionAdapter.getCoordinates();
				for(ExcursionCoordinate coord : coordinates) {
					coord.setExcursion(excursion);
					coord.setId(excursionCoordDAO.insert(coord));
				}
				
				List<Poi> pois = excursionAdapter.getPois();
				for(Poi poi : pois) {
					poi.setExcursion(excursion);
					poi.setId(poiDAO.insert(poi));
				}
				
			}
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
